<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="'姓名'" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.sex" :placeholder="'性别'" clearable style="width: 120px" class="filter-item">
        <el-option :label="'男'" :value="0"/>
        <el-option :label="'女'" :value="1"/>
      </el-select>
      <el-select v-model="listQuery.interview_status" :placeholder="'面试状态'" clearable style="width: 120px" class="filter-item">
        <el-option :label="'未匹配'" :value="0"/>
        <el-option :label="'待面试'" :value="1"/>
        <el-option :label="'一面中'" :value="2"/>
        <el-option :label="'一面未通过'" :value="3"/>
        <el-option :label="'一面缺席'" :value="4"/>
        <el-option :label="'一面通过'" :value="5"/>
        <el-option :label="'二面中'" :value="6"/>
        <el-option :label="'二面未通过'" :value="7"/>
        <el-option :label="'二面缺席'" :value="8"/>
        <el-option :label="'二面通过'" :value="9"/>
        <el-option :label="'HR终面中'" :value="10"/>
        <el-option :label="'HR终面未通过'" :value="11"/>
        <el-option :label="'HR终面缺席'" :value="12"/>
        <el-option :label="'HR终面通过'" :value="13"/>
      </el-select>
      <el-select v-model="listQuery.education" :placeholder="'学历'" clearable style="width: 120px" class="filter-item">
        <el-option label="不限" value="不限"/>
        <el-option label="大专" value="大专"/>
        <el-option label="本科" value="本科"/>
        <el-option label="硕士/研究生" value="硕士/研究生"/>
        <el-option label="博士/研究生" value="博士/研究生"/>
      </el-select>
      <el-input v-model="listQuery.recommend" placeholder="推荐岗位" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button v-if="list" :disabled="list.length===0" class="filter-item" icon="el-icon-download" type="success" @click="exportExcel">导出</el-button>
      <div style="display: flex;">
        <!--<el-upload-->
        <!--:action="multUploadUrl"-->
        <!--:on-preview="uploadHandlePreview"-->
        <!--:on-remove="uploadHandleRemove"-->
        <!--:before-remove="uploadBeforeRemove"-->
        <!--:on-exceed="uploadHandleExceed"-->
        <!--:on-success="uploadHandleSuccess"-->
        <!--:on-progress="uploadProgress"-->
        <!--multiple-->
        <!--class="upload-demo">-->
        <!--<el-button size="small" type="warning">点击上传</el-button>-->
        <!--<div slot="tip" class="el-upload__tip">只能上传xlsx和xls文件，且不超过5Mb</div>-->
        <!--</el-upload>-->
        <el-button type="success" @click="readyUploadHanlder">人才信息导入</el-button>
        <el-button style="margin-left: 20px" type="text" @click="downloadTemplate">模板下载</el-button>
      </div>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;">
      <!--<el-table-column :label="'序号'" prop="id" align="center" width="65">-->
      <!--<template slot-scope="scope">-->
      <!--<span>{{ scope.row.id }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'姓名'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'推荐职位'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.recommend }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'性别'" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sex_name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'出生日期'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.birthday }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'学历'" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.education }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'学校'" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.university }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'专业'" class-name="status-col" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.profession }}</span>
        </template>
      </el-table-column>
      <el-table-column label="招聘状态" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.interview_status_name }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column :label="'录用状态'" class-name="status-col" align="center">-->
      <!--<template slot-scope="scope">-->
      <!--<span :class="{success: scope.row.offer_status === true}">{{ scope.row.offer_status_name }}</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="'完整简历'" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-upload :action="uploadResumeUrl" :headers="uploadHeaders" :data="uploadData(scope.row.id)" :on-success="uploadSuccess">
            <el-button size="small" type="primary">上传简历</el-button>
          </el-upload>
          <a v-if="scope.row.resume" :href="scope.row.resume" target="_blank"><el-button type="text">预览简历</el-button></a>
        </template>
      </el-table-column>
      <el-table-column :label="'操作'" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="showWaitButton(scope.row.interview_status)" type="success" size="mini" @click="handleInterview('wait', scope.row.id)">待面试</el-button>
          <!--<el-button v-if="showSecondButton(scope.row.interview_status)" type="success" size="mini" @click="handleInterview('second', scope.row.id)">二面</el-button>-->
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" layout="total, prev, pager, next" @pagination="getList" />

    <el-dialog :title="dialogStatus === 'create' ? '新建人才' : '编辑人才'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item :label="'姓名：'" prop="name">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item :label="'推荐职位：'" prop="recommend">
          <el-input v-model="temp.recommend"/>
        </el-form-item>
        <el-form-item :label="'初次推荐：'" prop="first_recommend">
          <el-date-picker
            v-model="temp.first_recommend"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="'性别：'" prop="sex">
          <el-radio-group v-model="temp.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="'出生日期：'" prop="birthday">
          <el-date-picker
            v-model="temp.birthday"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="'学历：'" prop="education">
          <el-select v-model="temp.education" class="filter-item">
            <el-option label="大专" value="大专"/>
            <el-option label="本科" value="本科"/>
            <el-option label="硕士/研究生" value="硕士/研究生"/>
            <el-option label="博士/研究生" value="博士/研究生"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="'学校：'" prop="university">
          <el-input v-model="temp.university"/>
        </el-form-item>
        <el-form-item :label="'专业：'" prop="profession">
          <el-input v-model="temp.profession"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="waitDialogVisible" width="30%" title="待面试-面试批次">
      <el-form ref="waitForm" :model="waitForm" label-width="80px">
        <el-form-item label="面试时间">
          <el-date-picker v-model="waitForm.time" type="datetime" placeholder="请选择面试时间" value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="面试组别">
          <el-select v-model="waitForm.group" clearable placeholder="请选择组别">
            <el-option label="A" value="A"></el-option>
            <el-option label="B" value="B"></el-option>
            <el-option label="C" value="C"></el-option>
            <el-option label="D" value="D"></el-option>
            <el-option label="E" value="E"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="waitDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="waitCreateData">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="secondDialogVisible" width="30%" title="二面-面试批次">
      <el-form ref="secondForm" :model="secondForm" label-width="80px">
        <el-form-item label="面试批次">
          <el-date-picker v-model="secondForm.time" type="datetime" placeholder="请选择面试时间" value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="面试组别">
          <el-select v-model="secondForm.group" clearable placeholder="请选择组别">
            <el-option label="A" value="A"></el-option>
            <el-option label="B" value="B"></el-option>
            <el-option label="C" value="C"></el-option>
            <el-option label="D" value="D"></el-option>
            <el-option label="E" value="E"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="secondDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="secondCreateData">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="uploadVisible"
      title="人才信息导入"
      width="50%">
      <el-form ref="uploadForm" :model="uploadForm" label-width="100px">
        <el-form-item label="所属项目：">
          <el-select v-model="uploadForm.project_id" placeholder="请选择项目">
            <el-option v-for="(item, index) in projects" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件：">
          <el-upload
            :action="multUploadUrl"
            :on-preview="uploadHandlePreview"
            :on-remove="uploadHandleRemove"
            :before-remove="uploadBeforeRemove"
            :on-exceed="uploadHandleExceed"
            :on-success="uploadHandleSuccess"
            :on-progress="uploadProgress"
            :before-upload="uploadBefore"
            :show-file-list="false"
            :data="uploadForm"
            multiple
            class="upload-demo">
            <el-button size="small" type="warning">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="">
          只能上传xlxs和xls格式文件，并且文件大小不超过5Mb
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadVisible = false">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchPv } from '@/api/article'
import { getToken } from '@/utils/auth'
import { getTalentList, createTalent, updateTalent, deleteTalent, sendWaiting, mulWaiting, sendSecond, sendWaiting2, downloadTemplate } from '@/api/talent'
import { exportTalentIndex } from '@/api/export'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { talentRules } from '@/utils/formRules'
import { getAllProjectList } from '@/api/project'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'TalentIndex',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      projects: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        sex: undefined,
        interview_status: undefined,
        education: undefined,
        recommend: undefined
      },
      queryString: '',
      multUploadUrl: `${process.env.BASE_API}/api/talent/upload`,
      uploadResumeUrl: `${process.env.BASE_API}/api/talent/upload_resume`,
      uploadHeaders: { Authorization: `Bearer ${getToken()}` },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        recommend: '',
        first_recommend: '',
        sex: 0,
        birthday: undefined,
        education: '',
        university: '',
        profession: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      waitDialogVisible: false,
      secondDialogVisible: false,
      pvData: [],
      rules: talentRules,
      downloadLoading: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      mulIds: undefined,
      waitForm: {
        id: undefined,
        time: undefined,
        group: undefined
      },
      secondForm: {
        id: undefined,
        time: undefined,
        group: undefined
      },
      uploadVisible: false,
      uploadForm: {
        project_id: undefined
      }
    }
  },
  created() {
    if (this.$route.query.recommend) {
      this.listQuery.recommend = this.$route.query.recommend
    }
    const type = this.$route.query.type
    if (type) {
      switch (type) {
        case 'a':
          this.listQuery.interview_status = 1
          break
        case 'b':
          this.listQuery.interview_status = 2
          break
        case 'c':
          this.listQuery.interview_status = 5
          break
        case 'd':
          this.listQuery.interview_status = 6
          break
        case 'e':
          this.listQuery.interview_status = 9
          break
        case 'f':
          this.listQuery.interview_status = 10
          break
        case 'g':
          this.listQuery.interview_status = 13
          break
      }
    }
    this.$nextTick(() => {
      this.getList()
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      getTalentList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.meta.pagination.total
        this.listQuery.page = response.data.meta.pagination.current_page++
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      let query = ''
      const name = this.listQuery.name
      const sex = this.listQuery.sex
      const interview_status = this.listQuery.interview_status
      const education = this.listQuery.education
      if (name) {
        query += `name=${name}&`
      }
      if (sex || sex === 0) {
        query += `sex=${sex}&`
      }
      if (interview_status || interview_status === 0) {
        query += `interview_status=${interview_status}&`
      }
      if (education) {
        query += `education=${education}&`
      }
      this.queryString = query
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        recommend: '',
        first_recommend: '',
        sex: 0,
        birthday: undefined,
        education: '',
        university: '',
        profession: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createTalent(this.temp).then(response => {
            this.getList()
            this.dialogFormVisible = false
            this.$message.success('创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateTalent(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$message.success('更新成功')
          })
        }
      })
    },
    handleDelete(row) {
      const id = row.id
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTalent(id).then(response => {
          this.getList()
          this.$message.success('删除成功')
        })
      }).catch(() => {})
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    uploadHandleRemove(file, fileList) {
      // console.log(file, fileList)
    },
    uploadHandlePreview(file) {
      // console.log(file)
    },
    uploadHandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    uploadBeforeRemove(file, fileList) {
      // return this.$confirm(`确定移除${file.name}？`)
    },
    uploadHandleSuccess(err) {
      if (err.status === 403) {
        this.$message.error(err.message)
      } else {
        this.$message.success('导入成功')
        this.getList()
        this.uploadVisible = false
      }
    },
    handleInterview(type, id) {
      // switch (type) {
      //   case 'wait':
      //     this.waitDialogVisible = true
      //     this.waitForm.id = id
      //     break
      //   case 'second':
      //     this.secondDialogVisible = true
      //     this.secondForm.id = id
      //     break
      // }
      this.$confirm('确定进入待面试状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sendWaiting2(id).then(response => {
          this.getList()
          this.$message.success('操作成功')
        })
      }).catch(() => {})
    },
    waitCreateData() {
      const id = this.waitForm.id
      const time = this.waitForm.time / 1000
      const group = this.waitForm.group
      sendWaiting(id, time, group).then(response => {
        this.waitDialogVisible = false
        for (const v of this.list) {
          if (v.id === response.data.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, response.data)
            break
          }
        }
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch(err => {
        console.log(err)
      })
    },
    secondCreateData() {
      const id = this.secondForm.id
      const time = this.secondForm.time / 1000
      const group = this.secondForm.group
      sendSecond(id, time, group).then(response => {
        this.secondDialogVisible = false
        for (const v of this.list) {
          if (v.id === response.data.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, response.data)
            break
          }
        }
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch(err => {
        console.log(err)
      })
    },
    handleSelectionChange(val) {
      const a = []
      val.forEach(item => {
        a.push(item.id)
      })
      this.mulIds = a
      console.log(this.mulIds)
    },
    mulWaiting() {
      const data = { ids: this.mulIds }
      mulWaiting(data).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.getList()
      })
    },
    showWaitButton(status) {
      return status === 0
    },
    showSecondButton(status) {
      return status === 5
    },
    uploadData(id) {
      const obj = {}
      obj.id = id
      return obj
    },
    uploadSuccess() {
      this.uploadVisible = false
      this.getList()
      this.$message.success('上传成功')
    },
    uploadProgress(event, file, fileList) {
      // console.log(event)
      // console.log(file)
    },
    exportExcel() {
      exportTalentIndex(this.listQuery).then(response => {
        window.location.href = response.data.url
      })
    },
    downloadTemplate() {
      downloadTemplate().then(res => {
        if (res.status === 200) {
          window.location.href = res.data
        }
      })
    },
    readyUploadHanlder() {
      this.uploadVisible = true
      getAllProjectList().then(res => {
        if (res.status === 200) {
          this.projects = res.data.data
        }
      })
    },
    uploadBefore() {
      if (this.uploadForm.project_id === undefined) {
        this.$message.error('请先选择所属项目')
        return false
      }
    }
  }
}
</script>

<style scoped>
  .success {
    color: #67C23A;
  }
</style>
